<script setup lang="tsx">
import { ref, reactive, unref, shallowRef, provide } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Table } from '@/components/Table'
import { ElCollapseTransition, ElMessage } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { BaseButton } from '@/components/Button'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { getListApi, getPassApi, type Row } from '@/api/finance'
import { searchProductCateApi } from '@/api/utils/search'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'
const infoData = ref({})

defineOptions({
  name: 'Bill'
})
const searchRef = ref()
const projectSelectLoading = ref(false)
const projectSelectOptions = ref([])
const searchProject = async (query) => {
  if (query) {
    searchRef.value?.setSchema([
      {
        field: 'company_id',
        path: 'componentProps.loading',
        value: true
      }
    ])
    console.log(query)
    const res = await searchProductCateApi({ name: query, field: 'id,name' })
    if (res) {
      searchRef.value?.setSchema([
        {
          field: 'company_id',
          path: 'componentProps.options',
          value: res.data.list.map((item) => {
            return {
              label: item.name,
              value: item.id
            }
          })
        }
      ])
    }
    searchRef.value?.setSchema([
      {
        field: 'company_id',
        path: 'componentProps.loading',
        value: false
      }
    ])
  }
}
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    type: 'selection'
  },
  {
    field: 'id',
    label: '账单编号',
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'no',
    label: '关联订单号',
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'company_name',
    label: '公司名称',
    search: {
      field: 'company_id',
      component: 'Select',
      componentProps: {
        placeholder: '支持模糊搜索',
        filterable: true,
        remote: true,
        loading: projectSelectLoading.value,
        remoteMethod: searchProject,
        options: projectSelectOptions.value
      }
    },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'settlement_status',
    label: '状态',
    search: {
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '待结算',
            value: 1
          },
          {
            label: '已结算',
            value: 2
          }
        ]
      }
    },
    form: { hidden: true },
    detail: { hidden: true },
    formatter: (cellValue) => {
      return cellValue.settlement_status_text
    }
  },
  {
    field: 'total_money',
    label: '订单金额',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'real_money',
    label: '实际应得金额',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'pay_type_text',
    label: '支付方式',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'company_profit',
    label: '合伙人提成',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'driver_profit',
    label: '司机提成',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'platform_profit',
    label: '平台提成',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  }
])
// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)
const ids = ref<string[]>([])

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    infoData.value = res.data
    return {
      list: res.data.list,
      total: res.data.count
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose } = tableMethods

const showCollapse = ref(false)
let currentAction = shallowRef()
let currentRow = reactive<any>({})
const delLoading = ref(false)

const onSubmit = async (row: Row | null) => {
  const elTableExpose = await getElTableExpose()
  const list = elTableExpose?.getSelectionRows().map((v: Row) => v.settlement_status)
  if (unref(list).includes(2)) {
    ElMessage('已结算状态不能审核啊！')
    return
  }
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: Row) => v.id) || []
  console.log(ids.value.length)
  if (ids.value.length == 0) {
    ElMessage('请选择！')
    return
  }
  delLoading.value = true
  const res = await getPassApi({ order_ids: unref(ids.value).join(',') })
  if (res) {
    delLoading.value = false
    ElMessage.success(res.msg)
    getList()
  }
}

const closeCollapse = () => {
  showCollapse.value = false
}
// 导出
const exportToExcel = async () => {
  const res = await getListApi({
    page: 1,
    limit: 10,
    is_export: 1
  })
  const list = res.data.list.map((res) => {
    return {
      账单编号: res.id,
      关联订单号: res.no,
      公司名称: res.company_name,
      状态: res.settlement_status_text,
      订单金额: res.total_money,
      实际应得金额: res.real_money,
      支付方式: res.pay_type_text,
      合伙人提成: res.company_profit,
      司机提成: res.driver_profit,
      平台提成: res.platform_profit
    }
  })
  // 将数据转换为工作表
  const ws = XLSX.utils.json_to_sheet(list)
  // 创建工作簿并添加工作表
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
  // 生成 Excel 文件并保存
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
  saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '账单列表.xlsx')
}

provide('currentRow', currentRow)
</script>

<template>
  <ContentWrap title="账单列表">
    <Search
      ref="searchRef"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <BaseButton :loading="delLoading" type="primary" @click="onSubmit(null)">审核通过</BaseButton>
      <!-- <BaseButton :loading="delLoading" type="danger" @click="delData(null)">删除</BaseButton> -->
      <BaseButton type="primary" @click="exportToExcel()">导出</BaseButton>
    </div>

    <el-collapse-transition>
      <component
        :is="currentAction"
        :key="currentRow.id"
        @close="closeCollapse"
        @get-list="getList"
        v-if="showCollapse"
      />
    </el-collapse-transition>
    <div
      style="
        display: inline-block;
        width: auto;
        height: 40px;
        border: 1px solid #ccc;
        margin: 10px 0px;
        text-align: center;
        line-height: 40px;
        margin-right: 20px;
        padding: 0px 10px;
        box-sizing: border-box;
      "
      >全部金额（元）：{{
        (Number(infoData.unsettled_money) + Number(infoData.settled_money)).toFixed(2)
      }}</div
    >
    <div
      style="
        display: inline-block;
        width: auto;
        height: 40px;
        border: 1px solid #ccc;
        margin: 10px 0px;
        text-align: center;
        line-height: 40px;
        margin-right: 20px;
        padding: 0px 10px;
        box-sizing: border-box;
      "
      >待结算（元）：{{ infoData.unsettled_money }}</div
    >
    <div
      style="
        display: inline-block;
        width: auto;
        height: 40px;
        border: 1px solid #ccc;
        margin: 10px 0px;
        text-align: center;
        line-height: 40px;
        margin-right: 20px;
        padding: 0px 10px;
        box-sizing: border-box;
      "
      >已结算（元）：{{ infoData.settled_money }}</div
    >

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{ total }"
      @register="tableRegister"
    />
  </ContentWrap>
</template>
